package cn.cupk.logsystem.log.factoryPattern;

import cn.cupk.logsystem.log.observerPattern.Handler;
import cn.cupk.logsystem.log.LogRecord;

import java.io.FileWriter;
import java.io.IOException;

public class XmlHandler extends Handler {
    private final FileWriter writer;

    public XmlHandler(String filename, boolean append) throws IOException {
        String filePath = "D:/IdeaProjects/CODE/log-system/" + filename;
        writer = new FileWriter(filePath, append);
        System.out.println("XmlHandler initialized with file: " + filePath); // 调试信息
    }

    @Override
    public void publish(LogRecord record) {
        System.out.println("Publishing to XML file: " + record.getMessage()); // 调试信息
        try {
            if (getFormatter() != null) {
                writer.write(getFormatter().format(record));
            } else {
                writer.write(record.getMessage() + "\n");
            }
            writer.flush();
            System.out.println("Successfully wrote to XML file."); // 调试信息
        } catch (IOException e) {
            System.err.println("Failed to write to XML file: " + e.getMessage()); // 错误信息
            e.printStackTrace();
        }
    }

    @Override
    public void flush() {
        try {
            writer.flush();
        } catch (IOException e) {
            System.err.println("Failed to flush to XML file: " + e.getMessage()); // 错误信息
            e.printStackTrace();
        }
    }

    @Override
    public void close() throws SecurityException {
        try {
            writer.close();
            System.out.println("XmlHandler closed."); // 调试信息
        } catch (IOException e) {
            System.err.println("Failed to close XML file writer: " + e.getMessage()); // 错误信息
            e.printStackTrace();
        }
    }
}
